package gwtI18nEditor.filetools;

import gwtI18nEditor.datamodel.TranslationFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PropertiesFileParser {
	
	//TODO: Allow for comments, line-wraps and literal lines
	private static final String IDENTIFIER    = "[\\p{L}_$][\\p{L}\\p{N}_$]*?";
	private static final String FILE_NAME     = "("+IDENTIFIER+")(?:_([a-z]{2})(?:_([A-Z]{2}))?)?.properties";
	private static final String ENTRY_PATTERN = "\\s*("+IDENTIFIER+")[ \\t]*[=:][ \\t]*(.*?)[ \\t]*$\\s*";

	private static final Pattern NAME_PARSER  = Pattern.compile(FILE_NAME,     Pattern.MULTILINE);
	private static final Pattern ENTRY_PARSER = Pattern.compile(ENTRY_PATTERN, Pattern.MULTILINE);
	
	public static TranslationFile parseFile(File file) {
		try {
			// Read entire file into string
			FileInputStream stream = new FileInputStream(file);
			byte[] content = new byte[stream.available()];
			stream.read(content, 0, content.length);
			stream.close();
			String text = new String(content);
			
			Matcher matcher = NAME_PARSER.matcher(file.getName());
			if ((!matcher.matches()) || (matcher.groupCount()<2)) return null;
			String identifier = matcher.group(1);
			String language   = matcher.group(2);
			String country    = matcher.group(3);
			
			// Parse out filename to determine language
			TranslationFile result = new TranslationFile(identifier, language, country);

			// Parse out file entries
			matcher = ENTRY_PARSER.matcher(text);
			int lastEnd = 0;
			while (matcher.find()) {
				if (matcher.groupCount()!=2) return null;
				result.addEntry(matcher.group(1), matcher.group(2));
				lastEnd = matcher.end();
			}
			
			// Make sure entire file body was matched so that we won't loose
			// data if we rebuild the file later
			if (lastEnd!=text.length()) return null;
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
